Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Python Array → Sort Arrays

Python Array

Sort Arrays

Sorting Arrays (Lists) in Python

In Python, arrays are typically represented using lists. Lists are dynamic, ordered collections of items. They can hold elements of different data types, but sorting generally requires that all elements are comparable (e.g., all numbers or all strings). Let's explore several ways to sort lists in Python, with detailed explanations and examples.

1. Using the `list.sort()` method

The `sort()` method modifies the original list *in-place*. This means it doesn't create a new sorted list; it directly alters the existing one. It's efficient for large lists because it avoids creating a copy.
Sorting Arrays using `list.sort()` method my_list = [3, 1, 4, 1, 5, 9, 2, 6] my_list.sort() # Sorts in ascending order by default print(f"Sorted list (in-place): {my_list}") my_list.sort(reverse=True) # Sorts in descending order print(f"Sorted list (descending, in-place): {my_list}") #Sorting a list of strings string_list = ["banana", "apple", "orange", "grape"] string_list.sort() print(f"Sorted string list (in-place): {string_list}")

Output

Sorted list (in-place): [1, 1, 2, 3, 4, 5, 6, 9] Sorted list (descending, in-place): [9, 6, 5, 4, 3, 2, 1, 1] Sorted string list (in-place): ['apple', 'banana', 'grape', 'orange']

2. Using the `sorted()` function

The `sorted()` function creates a *new* sorted list, leaving the original list unchanged. This is useful when you need to preserve the original order of the list.
Sorting Arrays using `sorted()` function my_list = [3, 1, 4, 1, 5, 9, 2, 6] sorted_list = sorted(my_list) print(f"Original list: {my_list}") print(f"Sorted list (new list): {sorted_list}") sorted_list_desc = sorted(my_list, reverse=True) print(f"Sorted list (descending, new list): {sorted_list_desc}") #Sorting a list of tuples based on a specific element tuple_list = [(1, 'z'), (2, 'a'), (3, 'b')] sorted_tuples = sorted(tuple_list, key=lambda x: x[1]) #Sorts based on the second element of each tuple print(f"Sorted tuples based on second element: {sorted_tuples}")

Output

Original list: [3, 1, 4, 1, 5, 9, 2, 6] Sorted list (new list): [1, 1, 2, 3, 4, 5, 6, 9] Sorted list (descending, new list): [9, 6, 5, 4, 3, 2, 1, 1] Sorted tuples based on second element: [(2, 'a'), (3, 'b'), (1, 'z')]

3. Sorting with custom key functions

Both `sort()` and `sorted()` accept an optional `key` argument. The `key` argument should be a function that takes a single element from the list and returns a value used for comparison. This allows you to sort based on criteria other than the natural order.
Sorting with custom key functions in python # Sorting a list of objects class Person: def __init__(self, name, age): self.name = name self.age = age def __repr__(self): # For nicer printing return f"Person(name='{self.name}', age={self.age})" people = [Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35)] # Sort by age people.sort(key=lambda person: person.age) print(f"Sorted by age: {people}") # Sort by name people.sort(key=lambda person: person.name) print(f"Sorted by name: {people}")

Output

Sorted by age: [Person(name='Bob', age=25), Person(name='Alice', age=30), Person(name='Charlie', age=35)] Sorted by name: [Person(name='Alice', age=30), Person(name='Bob', age=25), Person(name='Charlie', age=35)]

Remember to choose the sorting method that best suits your needs – in-place modification with `list.sort()` for efficiency when you don't need the original list, or `sorted()` for creating a new sorted list while preserving the original. The `key` argument provides powerful customization for sorting based on specific criteria. For numerical arrays, `numpy` offers optimized performance.

Tutorials